<?php

namespace app\admin\service;

use Illuminate\Database\Eloquent\Builder;

/**
 * 基础服务类
 * 封装通用的服务层操作
 */
class BaseCurdService
{
    /**
     * 通用分页查询方法
     * @param Builder $query 查询构造器
     * @param array $params 查询参数
     * @param array $fields 模糊查询字段
     * @param array $exactFields 精确查询字段
     * @param array $orders 排序字段 ['field' => 'direction']，默认按id倒序
     * @return array
     */
    protected function paginateQuery(Builder $query, array $params, array $fields = [], array $exactFields = [], array $orders = ['id' => 'desc']): array
    {
        // 处理模糊查询字段
        foreach ($fields as $field => $value) {
            $fieldKey = is_int($field) ? $value : $field;
            if (!empty($params[$fieldKey])) {
                $query->where($fieldKey, 'like', '%' . $params[$fieldKey] . '%');
            }
        }
        // 处理精确查询字段
        foreach ($exactFields as $field => $value) {
            $fieldKey = is_int($field) ? $value : $field;
            if (!empty($params[$fieldKey])) {
                $query->where($fieldKey, $params[$fieldKey]);
            }
        }
        // 处理排序
        foreach ($orders as $field => $direction) {
            $query->orderBy($field, $direction);
        }
        $paginator = $query->paginate($params['limit'], ['*'], 'page', $params['page']);
        return [
            'page' => (int)$params['page'],
            'limit' => (int)$params['limit'],
            'count' => $paginator->total(),
            'list' => $paginator->items(),
        ];
    }
}